<template>
  <div >
    <div v-if="progress == 0" style="display:flex;justify-content:space-between;margin: 5%;">
      <input style="border:1px solid #13ce66;width:74%;height: 40px;line-height: 40px;padding-left:1rem;border-radius: 4px" type="file"  @change="handleFileChange" />

      <el-button type="success"  @click="uploadFile" style="margin-left: 5%;width:20%;">上传文件</el-button>

    </div>
    <div v-else style="margin: 5%">
      <el-progress :percentage="progress"></el-progress>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import  {initiate , chunk , complete} from "@/api/shareDrive/upload";
import { getToken } from '@/utils/auth'

export default {
  name:"upload",
  data() {
    return {
      file: null,
      chunkSize: 1024 * 1024 * 5, // 5MB per chunk
      totalChunks: 0,
      uploadedChunks: 0,
      progress: 0,
      fileId: '' // This will be provided by the backend after initiating the upload
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
    },
    async initiateUpload() {
      const formData = new FormData();
      if(this.file == null){
        this.progress = 0;
        this.fileId = ''
        this.$message.error('未发现文件');
        return;
      }
      formData.append('fileName', this.file.name);
      await initiate(formData).then(response => {
        this.fileId = response.data.fileId;
      }).catch(error => {
        this.progress = 0;
        this.fileId = ''
        this.file = null;
      });
    },
    async uploadChunk(chunk1) {
      const formData = new FormData();
      formData.append('chunk', chunk1);
      formData.append('fileId', this.fileId);
      formData.append('chunkNumber', this.uploadedChunks + 1);
      formData.append('totalChunks', this.totalChunks);

      await chunk(formData).then(response => {
        this.uploadedChunks++;
        this.progress = Math.floor((this.uploadedChunks / this.totalChunks) * 100);
      });
    },
    async uploadFile() {
      this.progress = 1

      const nowTime = new Date().getTime();
      await this.initiateUpload();
      console.log("----initiateUpload----", (new Date().getTime() - nowTime) / 1000 , "ss")
      if(this.fileId == ''){
        return;
      }
      const totalChunks = this.totalChunks;
      for (let start = 0; start < this.file.size; start += this.chunkSize) {
        const end = Math.min(start + this.chunkSize, this.file.size);
        const chunk = this.file.slice(start, end);

        await this.uploadChunk(chunk);
      }

      await complete(this.fileId).then(response => {
        this.progress = 0;
        this.uploadedChunks = 0;
        this.file = null;
        this.$message.success('上传成功');
      });

      // // Optionally, notify the backend that all chunks have been uploaded
      // await axios.post(process.env.VUE_APP_BASE_API + `/shareDive/upload/complete/${this.fileId}`,null,{
      //   headers: {
      //     'Authorization': 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      //   }
      // });

    }
  }
};
</script>
